/**
 * Created by chourongqishi on 2017/1/2.
 */

module.exports = function ($scope, $rootScope, $state, settingService,httpservice,$cookies,paginationService,registerSuccessService,Upload) {
  $rootScope.showCaseDiv = false;


    var expireDate = new Date();
    expireDate.setDate(expireDate.getDate() + 1);

    $scope.headImageUrl = "";
    $scope.userName = "";
    $scope.userShortName = "";
    $scope.professionType = "";
    $scope.professionNumber = "";
    $scope.professionCompany = "";
    $scope.entryDate = "";
    $scope.userBaseInfo = "";
    $scope.userBaseInfo_back = "";
    $scope.authState = ''; //获取认证状态 审核状态： 0-未审核 1-审核中 2-审核通过 3-审核失败
    $scope.staticState = true;    //控制label项
    $scope.bsinfobj = false;    //控制编辑项
    $scope.allSpanState = true;    //控制编辑项
    $scope.allInputState = false;    //控制编辑项
    $scope.editBaseButtonState = true;  //基本信息编辑按钮
    $scope.workStaticState = true;    //控制label项
    $scope.workinfobj = false;    //控制编辑项
    $scope.workAllSpanState = true;    //控制编辑项
    $scope.workAllInputState = false;    //控制编辑项
    $scope.editSkillButtonState = true;  //执业信息编辑按钮

    $scope.updateName = "";
    $scope.inputType = "";
    $scope.inputNumber = "";
    $scope.inputCompany = "";
    $scope.lawfirmId = "";
    $scope.inputDate = "";

    $scope.myemail = "";
    $scope.myHead2 = "";

    $scope.inputFYPlaceInput = '';
    $scope.FYID = '';

    $scope.attestStep = 1; //实名认证初始步骤
    $scope.errorFileShow = false; //图片上传失败信息显示标示
    $scope.errorFileMsg = "上传失败请您重新上传"; //图片上传失败信息显示标示
    $scope.skilledList = [];    //擅长领域标签列表
    $scope.userSkilledList = [];    //擅长领域列表
    $scope.selSkillIdVal = '';
    $scope.selSkillNameVal = '';

    $scope.degreeList = []; //学位列表
    $scope.provinceList = []; //省份列表
    $scope.getLawfirmList = getLawfirmList;
    $scope.findProvinceList = findProvinceList; //获取省份

    $scope.tabChangeZy = true
    $scope.tabChangeid = false



    $scope.pageSetting3 = paginationService.getDefaultPageSetting();
    $scope.pageSetting3.pageSize = 5;
    //上传
    $scope.uploadFile = uploadFile;
    $scope.cancelEditSkilled = cancelEditSkilled;
    $scope.removeBox = removeBox;

    //头像上传部分
    $scope.myImage='';
    $scope.myCroppedImage='';
    $scope.file = '';
    $scope.size='small';
    $scope.type='circle';
    $scope.resImgFormat='image/png';
    $scope.resImgQuality=1;
    $scope.selMinSize=100;
    $scope.resImgSize=200;
    $scope.isSelectHeadPhone = false;
    //头像上传部分

    $scope.attesInfo = {};

    /*登录ID*/
    $scope.loginId = kbt.decrypt($cookies.get('cookieUserId'));
    $scope.init = function () {
        $scope.isOpenSafe();
        $scope.queryUserInfo();
        $scope.queryLawFirms();
        //查询是否绑定过邮箱
        $scope.getBindEmail();
        //查询是否绑定过手机
        $scope.getBindPhone ();

        //获取学位列表
        $scope.getLawfirmList();

        $scope.findProvinceList();
    };

    //单独设置w5c表单验证
    $scope.w5cSkillValidateOptions = {
        blurTrig   : true,
        showError  : false,
        removeError: true
    };
    //单独设置w5c表单验证
    $scope.w5cSkillValidateOptionsEdit = {
        blurTrig   : true,
        showError  : false,
        removeError: true
    };

  //单独设置w5c表单验证
  $scope.w5cWorkInfoValidateOptions = {
    blurTrig   : true,
    showError  : false,
    removeError: false
  };

  //单独设置w5c表单验证
  $scope.w5cBaseInfoValidateOptions = {
    blurTrig   : true,
    showError  : false,
    removeError: false
  };

    /*执业证号离开焦点*/
    $("#license-no").blur(function () {
        checkLicense();
    })

    /*手机号码离开焦点*/
    $("#phoneNum").blur(function () {
        checkPhone();
    })


    /*执业证号输入验证*/
    function checkLicense() {
        if ($scope.inputNumber != "") {
            var len = $scope.inputNumber.length;
            if (!validate(len) || len != 17) {
                $(".error_number").fadeIn;
            } else {
                $(".error_number").fadeOut;
            }
        }
    }

    /*js 正则验证只输入数字*/
    function validate(value) {
        var reg = new RegExp("^[0-9]*$");
        if (!reg.test(value)) {
            return false;
        } else if (!/^[0-9]*$/.test(value)) {
            return false;
        } else {
            return true;
        }
    }

    function checkPhone() {
        var phone = $scope.ngNum;
        if (!(/^1[34578]\d{9}$/.test(phone))) {
            $("#wrong-num-hint").show();
        } else {
            $("#wrong-num-hint").hide();
        }
    }

    /*验证手机号的正则表达式*/
    function checkPhone2(phone){
        var phone = phone;
        if(!(/^1[34578]\d{9}$/.test(phone))){
            return false;
        }else{
            return true;
        }
    };
  /*验证手机号的正则表达式*/
  function checkEmail2(email){
    var email = email;
    // if(!(/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/.test(email))){
     if(email !=null){
      return false;
    }else{
      return true;
    }
  };
  function changePhone(phone){
    var str = phone.substr(0,2)+"*******"+phone.substr(9);
    return str;
  }
  function changeEmail(email){
    var c=email.split("@");
    var c1=c[0].substr(3);
    var xing="";
    for(var i=0;i<c1.length;i++){
      xing+="*";
    }
    var myemail=c[0].substr(0,2)+xing+"@"+c[1];
    return myemail
  }

    /**
     * 日期选择器
     */
    $(".form_datetime").datetimepicker({
        minView: "month",
        format: 'yyyy-mm-dd',
        language: "zh-CN",
        charset: "utf-8"
    });

    /**
     * 更改日期事件
     */
    $('.form_datetime')
        .datetimepicker()
        .on('changeDate', function (ev) {
            $('.form_datetime').datetimepicker('hide');
        });

  /*实名认证-入职年份*/
  $(".form_datetime_ym").datetimepicker({
    minView: 3,//设置最小视图为年视图
    format: 'yyyy-mm',
    language: "zh-CN",
    charset: "utf-8",
    startView: 3, //这里就设置了默认视图为年视图
    maxView:'decade',
    endDate:new Date()
  });

  /**
   * 更改日期事件
   */
  $('.form_datetime_ym')
    .datetimepicker()
    .on('changeDate', function (ev) {
      $('.form_datetime_ym').datetimepicker('hide');
    });




    /**
     * 判断是否为中文
     * @param temp
     * @returns {boolean}
     */
    function isChinese(temp) {
        var re = /[^\u4e00-\u9fa5]/;
        if (re.test(temp)) return false;
        return true;
    }

    // 是否是默认图片
    function isDefaultHeaderImage() {
        // if ($scope.headImageUrl == "img/user_info_head.png"){
        //     $scope.updateShortName($scope.userName);
        //     $(".shortDiv").show();
        // }
        // else {
        //     $(".shortDiv").hide();
        // }
        $scope.updateShortName($scope.userName);
    };

    // 查询用户信息
    $scope.queryUserInfo = function () {
        $rootScope.loadingShow = true;
        $rootScope.fadeShow = true;
        settingService.queryUserInfo().then(function (response) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            if (response.code == 1) {
                $scope.userName = response.data.username;
                $scope.professionType = response.data.profession;
                $scope.professionNumber = response.data.certificateno;
                $scope.professionCompany = response.data.lawfirmname;
                $scope.lawfirmId = response.data.lawfirmid;
                $scope.entryDate = response.data.entryyear;
                $scope.authState = response.data.authState;

                $scope.userBaseInfo = response.data;
                $scope.userBaseInfo.viewlawfirmname = $scope.userBaseInfo.lawfirmname;  //用户显示法律名称
                $scope.userBaseInfo.workArea = parseInt($scope.userBaseInfo.workArea); //强制转换类型，用于省份默认选中（保持数据类型一直才可选中 很严肃）

                $scope.userBaseInfo_back = angular.copy($scope.userBaseInfo); //备份原始数据


                var tempUrl = response.data.iconUrl;
                $scope.myHead2 = response.data.iconUrl;
                $scope.headImageUrl =tempUrl;
                //默认图片显示短名字
                isDefaultHeaderImage();
            }
        }, function (response) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            console.error('queryUserInfo error', response.status, response.statusText);
        });
    };

    // 查询律师事务所
    $scope.queryLawFirms = function () {
      $('.lsSearchName').show();
       var name = $scope.inputFYPlaceInput;
        settingService.queryLawFirms(name).then(function (response) {

            if (response.code == 1) {
                $scope.lawFirms = response.data;
            }
        }, function (response) {
           // console.error(response.status, response.statusText);
        });
    };

    //显示法院名
    $scope.showFYName = function () {
        $('.lsSearchName').show();
    }

    //点击法院的名字
    $scope.selectFYName = function (name,FYID) {
        $scope.inputFYPlaceInput = name;
        $scope.FYID = FYID;
        $('.lsSearchName').css('display','none');
    }


    // 无头像时，显示缩写名字
    $scope.updateShortName = function (name) {
        if (name != null || name != "") {
            if (isChinese(name)) {
                var nameSub = name.substr(name.length - 2);
                $scope.userShortName = nameSub;
            } else {
                var nameSub = name.substr(name.length - 5);
                $scope.userShortName = nameSub;
            }
        }
    };

    // 更改用户名
    $scope.updateUserName = function () {

        var text = $(".setuser-changename-btn").html().trim();
        if (text == "修改用户名") {
            $(".nameInput").show();
            $(".normal-name").hide();
            $(".setuser-changename-btn").html("保存");
            $(".update-name-cancel").show();
            $scope.updateName = $scope.userName;
        } else {
            //如果输入用户名与之前相同则不调接口
            if($('#setting-username').val()==$scope.userName){
                $(".normal-name").show();
                $(".nameInput").hide();
                $(".setuser-changename-btn").html("修改用户名");
                $(".update-name-cancel").hide();
            }else{
                $rootScope.loadingShow = true;
                $rootScope.fadeShow = true;
                settingService.updateUserName($scope.updateName).then(function (response) {
                    $rootScope.loadingShow = false;
                    $rootScope.fadeShow = false;

                    if (response.code == 1) {
                        $scope.userName = $scope.updateName;
                        $cookies.put('cookieUserName', kbt.encrypt($scope.updateName), {
                            expires: expireDate
                        });

                        isDefaultHeaderImage();

                        $(".normal-name").show();
                        $(".nameInput").hide();
                        $(".setuser-changename-btn").html("修改用户名");
                        $(".update-name-cancel").hide();

                        //刷新整个界面
                        window.location.reload();
                    }
                }, function (response) {
                    $rootScope.loadingShow = false;
                    $rootScope.fadeShow = false;
                    console.error('updateUserName error', response.status, response.statusText);
                });
            }

        }
    };

    $scope.updateProfessionInfo = function () {
        var text = $("#editProfession").html().trim();
        if (text == "编辑") {
            $(".list1").hide();
            $(".list2").show();
            $("#editProfession").html("保存");

            $scope.inputType = $scope.professionType;
            $scope.inputNumber = $scope.professionNumber;
            $scope.inputCompany = $scope.lawfirmId; // 显示名字，但是传入时要传入lawfirmId
            $scope.inputDate = $scope.entryDate;
            $scope.inputFYPlaceInput = $scope.professionCompany;
        } else {
            $rootScope.loadingShow = true;
            $rootScope.fadeShow = true;

            settingService.updateProfessionInfo($scope.inputType,$scope.inputNumber,$scope.FYID,$scope.inputDate)
                .then(function (response) {
                    $rootScope.loadingShow = false;
                    $rootScope.fadeShow = false;

                    if (response.code == 1) {
                        $scope.professionType = $scope.inputType;
                        $scope.professionNumber = $scope.inputNumber;
                        $scope.entryDate = $scope.inputDate;
                        $scope.professionCompany = $scope.inputFYPlaceInput;
                        $scope.lawfirmId = $scope.inputCompany;


                        $(".list1").show();
                        $(".list2").hide();
                        $("#editProfession").html("编辑");
                    }
                }, function (response) {
                    $rootScope.loadingShow = false;
                    $rootScope.fadeShow = false;
                    console.error('updateProfessionInfo error', response.status, response.statusText);
                });
        }
    };


    /**
     * 修改密码（知道原密码）
     */
    $scope.updataUserPasswordd=function(){

    }
    $scope.updateUserPassword = function () {
      if($scope.newPassword !=$scope.affirmPassWord & $scope.changePassWord!=false){
        $('#help-block').show();
        return;
      }else{
        // $('#help-block').hide();
        $('#changePassword').modal('hide');
        settingService.updateUserPassword($scope.oldPassWord, $scope.newPassword, $scope.affirmPassWord).then(function (response) {
          $rootScope.loadingShow = false;
          $rootScope.fadeShow = false;

          if (response.code == 1) {
            bootbox.dialog({
              message: "修改密码成功",
              title: "提示信息",
              buttons: {
                Cancel: {
                  label: "取消",
                  className: "btn-cancel",
                  callback: function () {

                  }
                },
                OK: {
                  label: "确定",
                  className: "btn-confirm",
                  callback: function () {
                    $scope.oldPassWord = '';
                    $scope.newPassWord = '';
                    $scope.affirmPassWord = '';
                  }
                }
              }
            });
            $scope.oldPassWord = '';
            $scope.newPassword = '';
            $scope.affirmPassWord = '';
          }
        }, function (response) {
          $rootScope.loadingShow = false;
          $rootScope.fadeShow = false;
          console.error('updateUserPassword error', response.status, response.statusText);
        });
      }


        // if ($scope.oldPassWord == "" || $scope.oldPassWord == null || $scope.oldPassWord == undefined) {
        //     bootbox.dialog({
        //     message: "原密码不能为空",
        //     title: "提示信息",
        //     buttons: {
        //       Cancel: {
        //         label: "取消",
        //         className: "btn-cancel",
        //         callback: function () {
        //
        //         }
        //       },
        //       OK: {
        //         label: "确定",
        //         className: "btn-confirm",
        //         callback: function () {
        //           $scope.oldPassWord = '';
        //           $scope.newPassWord = '';
        //           $scope.affirmPassWord = '';
        //         }
        //       }
        //     }
        //   });
        // } else if ($scope.newPassWord == "" || $scope.newPassWord == null || $scope.newPassWord == undefined) {
        //     bootbox.dialog({
        //     message: "新密码不能为空",
        //     title: "提示信息",
        //     buttons: {
        //       Cancel: {
        //         label: "取消",
        //         className: "btn-cancel",
        //         callback: function () {
        //
        //         }
        //       },
        //       OK: {
        //         label: "确定",
        //         className: "btn-confirm",
        //         callback: function () {
        //           $scope.oldPassWord = '';
        //           $scope.newPassWord = '';
        //           $scope.affirmPassWord = '';
        //         }
        //       }
        //     }
        //   });
        // } else if ($scope.affirmPassWord == "" || $scope.affirmPassWord == null || $scope.affirmPassWord == undefined) {
        //     bootbox.dialog({
        //     message: "确认密码不能为空",
        //     title: "提示信息",
        //     buttons: {
        //       Cancel: {
        //         label: "取消",
        //         className: "btn-cancel",
        //         callback: function () {
        //
        //         }
        //       },
        //       OK: {
        //         label: "确定",
        //         className: "btn-confirm",
        //         callback: function () {
        //           $scope.oldPassWord = '';
        //           $scope.newPassWord = '';
        //           $scope.affirmPassWord = '';
        //         }
        //       }
        //     }
        //   });
        // } else {
        //
        //     $rootScope.loadingShow = true;
        //     $rootScope.fadeShow = true;
        //     settingService.updateUserPassword($scope.oldPassWord, $scope.newPassWord, $scope.affirmPassWord).then(function (response) {
        //         $rootScope.loadingShow = false;
        //         $rootScope.fadeShow = false;
        //
        //         if (response.code == 1) {
        //           bootbox.dialog({
        //             message: "修改密码成功",
        //             title: "提示信息",
        //             buttons: {
        //               Cancel: {
        //                 label: "取消",
        //                 className: "btn-cancel",
        //                 callback: function () {
        //
        //                 }
        //               },
        //               OK: {
        //                 label: "确定",
        //                 className: "btn-confirm",
        //                 callback: function () {
        //                   $scope.oldPassWord = '';
        //                   $scope.newPassWord = '';
        //                   $scope.affirmPassWord = '';
        //                 }
        //               }
        //             }
        //           });
        //           $scope.oldPassWord = '';
        //           $scope.newPassWord = '';
        //           $scope.affirmPassWord = '';
        //             // $("#setsafe-edit-fixpwd").hide();
        //             // $("#setsafe-btn-fixpwd").show();
        //
        //         } else {
        //           bootbox.dialog({
        //             message: response.message,
        //             title: "提示信息",
        //             buttons: {
        //               Cancel: {
        //                 label: "取消",
        //                 className: "btn-cancel",
        //                 callback: function () {
        //
        //                 }
        //               },
        //               OK: {
        //                 label: "确定",
        //                 className: "btn-confirm",
        //                 callback: function () {
        //
        //                 }
        //               }
        //             }
        //           });
        //         }
        //     }, function (response) {
        //         $rootScope.loadingShow = false;
        //         $rootScope.fadeShow = false;
        //         console.error('updateUserPassword error', response.status, response.statusText);
        //     });
        // }
    };
  $scope.chep = validatePwd;
  $('#help-block').hide();
    function validatePwd(){
      if($scope.newPassword != $scope.affirmPassWord){
        $('#help-block').show();
        return;
      }else{
        $('#help-block').hide();
      }
    }

    /**
     * 查询是否绑定过邮箱
     */
    $scope.getBindEmail = function () {

        $rootScope.loadingShow = true;
        $rootScope.fadeShow = true;
        settingService.getBindEmail().then(function (response) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;

            if (response.code == 1) {
                $('#bind-email-text').html("已绑定邮箱为：" + changeEmail(response.data));
                $('#setsafe-btn-bind').text("更换邮箱");
            } else {
                $('#bind-email-text').html("未绑定邮箱，绑定邮箱可直接使用邮箱登录。");
                $('#setsafe-btn-bind').text("立即绑定");
            }
        }, function (response) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            console.error('getBindEmail error', response.status, response.statusText);
        });

    };

    /**
     * 绑定邮箱
     */
    $scope.saveBindEmail = function () {

        $rootScope.loadingShow = true;
        $rootScope.fadeShow = true;
        if ($scope.myemail == null || $scope.myemail == undefined || $scope.myemail == "") {
            alert("邮箱不能为空");
        } else if ($scope.myemail.indexOf("@") < 0) {
            alert("邮箱不合法");
        } else {
            settingService.saveBindEmail($scope.myemail).then(function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;

                if (response.code == 1) {
                    $('#bind-email-text').html("已绑定邮箱为：" + $scope.myemail);
                    $('#setsafe-edit-email').hide();
                    $("#setsafe-btn-bind").show();
                    $("#setsafe-btn-bind").text("更换邮箱")
                } else {
                    alert(response.message);
                }
            }, function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                console.error('saveBindEmail error', response.status, response.statusText);
            });
        }

    };

    /**
     * 修改邮箱
     */
    $scope.changeBindEmail = function () {

        $rootScope.loadingShow = true;
        $rootScope.fadeShow = true;
        if ($scope.oldEmail != null || $scope.oldEmail != undefined || $scope.oldEmail != "") {
          // } else if ($scope.newEmail == null || $scope.newEmail == undefined || $scope.newEmail == "") {
          //     alert("新邮箱不能为空");
          // } else if ($scope.confirmEmail == null || $scope.confirmEmail == undefined || $scope.confirmEmail == "") {
          //     alert("确认邮箱不能为空");
          // } else if ($scope.emailValidateCode != $scope.emailValidateCode) {

          // }
        // }else {
          $('.setsafe-identity').children('input').attr('disabled',false);

            settingService.changeBindEmail($scope.oldEmail,$scope.emailValidateCode).then(function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;

                if (response.code == 1) {
                    $('#bind-email-text').html("已绑定邮箱为：" + $scope.oldEmail);
                    // $('#setsafe-change-email').hide();
                    // $("#setsafe-btn-bind").show();
                    // $("#setsafe-btn-bind").text("更换邮箱")
                  $scope.oldEmail = '';
                  $scope.emailValidateCode = '';
                } else {
                  bootbox.dialog({
                    // message: "此文件类型不支持预览",
                    message: response.message,
                    title: "提示信息",
                    buttons: {
                      Cancel: {
                        label: "取消",
                        className: "btn-cancel",
                        callback: function () {

                        }
                      },
                      OK: {
                        label: "确定",
                        className: "btn-confirm",
                        callback: function () {

                        }
                      }
                    }
                  });
                }
            }, function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                console.error('changeBindEmail error', response.status, response.statusText);
            });
        }

    };

    /**
     * 查询是否绑定过手机
     */
    $scope.getBindPhone = function () {
        $rootScope.loadingShow = true;
        $rootScope.fadeShow = true;
        settingService.getBindPhone().then(function (response) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;

            if (response.code == 1) {
                $('#bind-phone-text').html("已绑定手机" + changePhone(response.data) + "，可直接用此手机登录平台。");
                $('#setsafe-btn-change').text("更换手机");
            } else {
                $('#bind-phone-text').html("未绑定手机号码，请绑定手机号码");
                $('#setsafe-btn-change').text("立即绑定");
            }
        }, function (response) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            console.error('getBindPhone error', response.status, response.statusText);
        });

    };


    /**
     * 绑定手机
     */
    $scope.saveBindPhone = function () {

        $rootScope.loadingShow = true;
        $rootScope.fadeShow = true;
        if ($scope.cellPhone == null || $scope.cellPhone == undefined || $scope.cellPhone == "") {
            alert("手机号不能为空");
        } else if ($scope.validateCode == null || $scope.validateCode == undefined || $scope.validateCode == "") {
            alert("验证码不能为空");
        } else {
            settingService.saveBindPhone($scope.cellPhone, $scope.validateCode).then(function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;

                if (response.code == 1) {
                    $('#bind-phone-text').html("已绑定手机" + $scope.cellPhone + "，可直接用此手机登录平台。");
                    $('#setsafe-edit-phone').hide();
                    $("#setsafe-btn-change").show();
                    $("#setsafe-btn-change").text("更换手机");
                } else {
                    alert(response.message);
                }
            }, function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                console.error('saveBindEmail error', response.status, response.statusText);
            });
        }

    };


    //点击获取验证码
    $scope.sendMesCod = function(){
        var phoneNum = $('#newPhone').val();
        //判断手机号111
        if(checkPhone2(phoneNum)){
            $scope.time();
            settingService.sendMesCod(phoneNum,6).then(function (data) {
                if (data.code == 1) {

                }
            },function (data) {

            });
        }
    };

    //手机点击获取验证码
    $scope.sendMesCod1 = function(){
        var newPhoneNum = $('#change-new-num').val();
        var oldPhoneNum = $('#change-old-num').val();
        //判断手机号
        if(checkPhone2(newPhoneNum,oldPhoneNum)){
            $scope.time();
            settingService.sendMesCod(newPhoneNum,oldPhoneNum,6).then(function (data) {
                if (data.code == 1) {

                }
            },function (data) {

            });
        }
    };

  //获取手机验证码倒计时
  var wait = 180;
  $scope.time = function (){
    if (wait == 0) {

      $('#getPhoneCode').attr("disabled",false);
      $('#getPhoneCode').val("获取验证码");
      wait = 180;
    } else {

      $('#getPhoneCode').attr("disabled",true);
      $('#getPhoneCode').val("重新发送（" + wait + "）");
      wait--;

      setTimeout(function () {
        $scope.time()
      }, 1800)
    }
  };

  //邮箱点击获取验证码
  $scope.sendMesCod2 = function(){
    var email = $('#newEmail').val();
     if(checkEmail2(email)){
       var params = {"email":email};
       $scope.time2();
      settingService.getEmailVerifyCode(params).then(function (data) {
        if (data.code == 1) {

        }
      },function (data) {

      });
    }
  };


    //获取验证码倒计时
    var wait2 = 180;
    $scope.time2 = function (){
        if (wait2 == 0) {

            $('#getEmailCode').attr("disabled",false);
            $('#getEmailCode').val("获取验证码");
            wait2 = 180;
        } else {


            $('#getEmailCode').attr("disabled",true);
            $('#getEmailCode').val("重新发送（" + wait2 + "）");

            wait2--;

            setTimeout(function () {
                  $scope.time2()
              }, 1800)
          }
    };


    /**
     * 修改手机
     */
    $scope.updateBindPhone = function () {

        $rootScope.loadingShow = true;
        $rootScope.fadeShow = true;
        if ($scope.oldCellPhone == null || $scope.oldCellPhone == undefined || $scope.oldCellPhone == "") {
          bootbox.dialog({
            message: "原密码不能为空",
            title: "提示信息",
            buttons: {
              Cancel: {
                label: "取消",
                className: "btn-cancel",
                callback: function () {

                }
              },
              OK: {
                label: "确定",
                className: "btn-confirm",
                callback: function () {

                }
              }
            }
          });
        } else if ($scope.newCellPhone == null || $scope.newCellPhone == undefined || $scope.newCellPhone == "") {
          bootbox.dialog({
            message: "新密码不能为空",
            title: "提示信息",
            buttons: {
              Cancel: {
                label: "取消",
                className: "btn-cancel",
                callback: function () {

                }
              },
              OK: {
                label: "确定",
                className: "btn-confirm",
                callback: function () {

                }
              }
            }
          });
        } else if ($scope.validateCode == null || $scope.validateCode == undefined || $scope.validateCode == "") {
          bootbox.dialog({
            message: "验证码不能为空",
            title: "提示信息",
            buttons: {
              Cancel: {
                label: "取消",
                className: "btn-cancel",
                callback: function () {

                }
              },
              OK: {
                label: "确定",
                className: "btn-confirm",
                callback: function () {

                }
              }
            }
          });
        } else {
            settingService.updateBindPhone($scope.oldCellPhone, $scope.newCellPhone, $scope.validateCode).then(function (response) {
                // $rootScope.loadingShow = false;
                // $rootScope.fadeShow = false;

                if (response.code == 1) {
                    $('#bind-phone-text').html("已绑定手机" + $scope.newCellPhone + "，可直接用此手机登录平台。");
                    // $('#setsafe-change-phone').hide();
                    // $("#setsafe-btn-change").show();
                    // $("#setsafe-btn-change").text("更换手机");
                  $scope.oldCellPhone = '';
                  $scope.newCellPhone = '';
                  $scope.validateCode = '';
                } else {
                  bootbox.dialog({
                    message: "手机号输入错误",
                    title: "提示信息",
                    buttons: {
                      Cancel: {
                        label: "取消",
                        className: "btn-cancel",
                        callback: function () {

                        }
                      },
                      OK: {
                        label: "确定",
                        className: "btn-confirm",
                        callback: function () {

                        }
                      }
                    }
                  });
                }
            }, function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                console.error('changeBindEmail error', response.status, response.statusText);
            });
        }

    };


    //账号安全
    $scope.isOpenSafe = function () {
      $('.tab-content').css('display','block');
      $('#set-safe').css('display','block');
      $('#set-msg').css('display','none');
      $('.lAccountSafe').addClass('L_settabActive');
      $('.lMessageSet').removeClass('L_settabActive');
    };


    //接受消息设置
    $scope.isOpenMessage = function () {
        $('.setDesTop').prop("checked",false);
        $('.setEmail').prop("checked",false);
        $('.setMessage').prop("checked",false);
        $('.setWeChat').prop("checked",false);
        $('#set-safe').css('display','none');
        $('#set-msg').css('display','block');
        $('.lMessageSet').addClass('L_settabActive');
        $('.lAccountSafe').removeClass('L_settabActive');
        settingService.isOpenSendMessage().then(function (data) {
            if(data.code == 1){
                for(var i=0;i<data.data.length;i++){
                    if(data.data[i].notificationId == "noDisturb"){
                        $('.setMessage').prop("checked",true);
                    }else if(data.data[i].notificationId == "weChat"){

                        $('.setWeChat').prop("checked",true);
                    }else if(data.data[i].notificationId == "email"){

                        $('.setEmail').prop("checked",true);
                    }else if(data.data[i].notificationId == "desktop"){
                        $('.setDesTop').prop("checked",true);
                    }
                }
            }
        });
    }






    $scope.init();
    /*初始化方法*/

    //消息设置

    //第一个,免打扰
    $('.setMessage').change(function () {
        if($('.setMessage').is(':checked')){
            settingService.changeSendMessage("noDisturb",1).then(function (data) {
                if(data.code == 1){
                    $scope.isOpenMessage();
                }
            })
        }else {
            settingService.changeSendMessage("noDisturb",0).then(function (data) {
                if(data.code == 1){
                    $scope.isOpenMessage();
                }
            })
        }

    });


    //微信
    $('.setWeChat').change(function () {
        if($('.setWeChat').is(':checked')){
            settingService.changeSendMessage("weChat",1).then(function (data) {
                if(data.code == 1){
                    $scope.isOpenMessage();
                }
            })
        }else {
            settingService.changeSendMessage("weChat",0).then(function (data) {
                if(data.code == 1){
                    $scope.isOpenMessage();
                }
            })
        }
    });

    //邮件
    $('.setEmail').change(function () {
        if($('.setEmail').is(':checked')){
            settingService.changeSendMessage("email",1).then(function (data) {
                if(data.code == 1){
                    $scope.isOpenMessage();
                }
            })
        }else {
            settingService.changeSendMessage("email",0).then(function (data) {
                if(data.code == 1){
                    $scope.isOpenMessage();
                }
            })
        }
    });

    //setDesTop
    $('.setDesTop').change(function () {
        if($('.setDesTop').is(':checked')){
            settingService.changeSendMessage("desktop",1).then(function (data) {
                if(data.code == 1){
                    $scope.isOpenMessage();
                }
            })
        }else {
            settingService.changeSendMessage("desktop",0).then(function (data) {
                if(data.code == 1){
                    $scope.isOpenMessage();
                }
            })
        }
    });


  //登录信息
  $scope.loginInfor = function (){
    var params = {"id":$scope.loginId,"pageNum":$scope.pageSetting3.pageNo,"pageSize":$scope.pageSetting3.pageSize}
    settingService.loginInfor(params).then(function (response) {
      $scope.loginInforList = response.data;
    })
  };
  $scope.loginInfor();


  $scope.clearForm = function(form) {
    $('#help-block').hide();

    // 迭代input清空
    $(':input', form).each(function () {
      var type = this.type;
      var tag = this.tagName.toLowerCase(); // normalize case
      if (type == 'text' || type == 'password' || tag == 'textarea')
        this.value = "";
      // 跌代多选checkboxes
      else if (type == 'checkbox' || type == 'radio')
        this.checked = false;
      // select 迭代下拉框
      else if (tag == 'select')
        this.selectedIndex = -1;
    });
  };

    //认证基本信息录入
    $scope.baseInfoStep = function(){
        if(JSON.stringify($scope.attesInfo) == "{}") {
            //获取已有认证信息
            settingService.findAttesInfo().then(function (response) {
                $scope.attesInfo = response.data.data;

            })
        }

        $scope.attestStep = 2;
    }

    //认证头像步骤
    $scope.phoneStep = function () {

        if(typeof($scope.attesInfo.layfirmname) == "object") {
            $scope.attesInfo.lawfirmid = $scope.attesInfo.layfirmname.id;
        } else {
          if ($scope.attesInfo.lawfirmid == undefined) {
            $("#zylawrzfirmname").addClass("error");
            $("#zylawrzfirmname").val("请选择律所");
            return false;
          }
        }

        if($scope.attesInfo.certificatephotoUrl) {
            $scope.attesInfo.picFile = $scope.attesInfo.certificatephotoUrl;
        } else {
           //$scope.attesInfo.picFile = 'img/w_imgBg.png';
        }
        $scope.attestStep = 3;
    }

    //提交信息并完成
    $scope.saveAttes = function (file) {

        if(!$scope.attesInfo.certificatephoto) {
            if(typeof(file) == "undefined") {
                $scope.errorFileShow = true;
                $scope.errorFileMsg = '请选择图片';
                return false;
            }
        }


        var fileSize = file != null ? Math.round(file.size/1024*100)/100 : 0;
        if(file != null && fileSize > (1024*6)){
            //$rootScope.messageAlert('上传文件大于6MB！');
            $scope.errorFileShow = true;
            $scope.errorFileMsg = '上传文件大于6MB！';
            return;
        }

        $scope.attesInfo.file = file;

        if(typeof($scope.attesInfo.layfirmname) == "object") {
            $scope.attesInfo.lawfirmid = $scope.attesInfo.layfirmname.id;
        }
        $scope.attesInfo.fileType = 'image';

        //certificatePhoto 原始图片路径

        if (file || $scope.attesInfo.certificatephoto) {
            file.upload = Upload.upload({
              url: httpservice.saveAttesUrl,
              data: $scope.attesInfo
            }).then(function (response) {
                if(response.data.code != 0){
                    $scope.attesInfo = {};
                    $scope.attestStep = 4;
                    $scope.authState = 1;   //认证信息提交成功后，修改认证状态。

                    return;
                }

            }, function (response) {
                if (response.status > 0)
                vm.errorMsg = response.status + ': ' + response.data;
            }, function (evt) {

            });
        }


    }

    //关闭认证窗体
    $scope.closeAttes = function () {
        $scope.attestStep = 1;
        angular.element("#certification").modal("hide");
        $scope.attesInfo = {};
        //window.location.reload();
    }

    $scope.getLawfirmList = function (name) {

        return registerSuccessService.getLawfirm(name).then(function (response) {
        if (response.data.code == 1) {
            return response.data.data;
        }
    })
  }

    function uploadFile (file) {

        $scope.attesInfo.picFile = file;
        $scope.attesInfo.certificatephoto = ''; //重新提交图片，将原有图片路径置空
    }

    $scope.tabSkilledzy = function () {
      $scope.tabChangeid = false;
        $scope.tabChangeZy = true;
    }

    //切换到擅长领域页面
    $scope.tabSkilled = function () {
        //alert($scope.tabChangeid);
        $scope.tabChangeid = true;
        $scope.tabChangeZy = false;
        //alert($scope.tabChangeid);
        //console.log($('#tabChangeid').attr('class'));
        //获取标签
        settingService.findSkilled().then(function (response) {
            $scope.skilledList = response.data.data;

        })
        //获取擅长领域
        settingService.findUserSkilled().then(function (response) {
            $scope.userSkilledList = response.data.data;
            //添加一个元素列表中备用
            for (var i=0; i<$scope.userSkilledList.length; i++)
            {
                $scope.userSkilledList[i].subDesc = $scope.userSkilledList[i].description
            }
            //添加一个元素列表中备用
        });
    }

    //擅长领域切换
    $scope.selTag = function(id, name) {
        $scope.selSkillIdVal = id;
        $scope.selSkillNameVal = name;
    }
    $(document).click(function(e){
        $scope.updateBoxTogger=true;
        if($scope.updateBoxTogger) {
            $('.updateBox').css('display', 'none');
        }
    });
    $scope.updateBoxTogger=false;
    //出现修改任务组的盒子
    $scope.showUpdateTaskBox = function ($event) {
      $event.stopPropagation();
        var $event = $event.target;
        var e = $($event);
       $('.updateBox').css('display', 'none');
        $(e).siblings('.updateBox').css('display','block');

    };
    //

    //移除box
    function removeBox ($event) {
        $event.stopPropagation();
        var $event = $event.target;
        var e = $($event);

        $(e).parents('.updateBox').css('display','none');
    };

    //选择编辑擅长领域
    $scope.goEditSkilled = function(id, $event) {
        removeBox($event);
        $("#static"+id).hide();
        $("#edit"+id).show();
    }

    //取消编辑
    function cancelEditSkilled (id) {
        $("#static"+id).show();
        $("#edit"+id).hide();
    }

    //操作框弹出
    $scope.nextShow = function (t) {
        //alert($(t).html()); //nextSibling(".updateBox").show();
    }

    //编辑擅长领域
    $scope.editSkilled = function (item, id) {
        //console.log($scope.userSkilledList[item]);

        var descinfo = $("#desc"+id).val();
        var info = "";
        if(descinfo.length < 200 || descinfo.length > 500) {
            info = "请输入不少于200字的描述";
        }
        if(info != ""){
          bootbox.alert({
            size: "small",
            title: "提示信息",
            message: info,
            callback: function(){ /* your callback code */ }
          });
          return false;
        }


        $scope.userSkilledList[item].description = $("#desc"+id).val();
        settingService.setUserSkilled( $scope.userSkilledList[item] ).then(function (response) {
            if (response.data.code == 1) {
                $scope.userSkilledList[item].description = $("#desc"+id).val(); //编辑成功时修改列表里的描述
                cancelEditSkilled(id);
                return ;
            }
        });
    }

    //删除擅长领域
    $scope.delSkilled = function (item, $event) {
      bootbox.dialog({
        message: "确定是否要删除该条擅长领域信息？",
        title: "提示信息",
        className:'d-promptBox',
        buttons: {
          OK: {
            label: "确定",
            className: "d-btn-confirm2",
            callback: function() {
              removeBox($event);
              //console.log($scope.userSkilledList[item]);
              var params = {id:$scope.userSkilledList[item].id };
              settingService.deleteUserSkilled( params ).then(function (response) {
                if (response.data.code == 1) {
                  $scope.userSkilledList.splice(item, 1);

                  return ;
                }
              });
            }
          },
          Cancel: {
            label: "取消",
            className: "d-btn-cancel",
            callback: function () {}
          }
        }
      })

    }

    //保存修改擅长领域
    $scope.saveSkilled = function() {


        if($scope.selSkillIdVal==""){
          bootbox.dialog({
            size: "small",
            title: "提示信息",
            className:'d-promptBox',
            message: "请选择擅长类型",
            buttons: {
              OK: {
                label: "关闭",
                className: "d-btn-confirm",
              }
            },
            callback: function(){ /* your callback code */ }
          });
          return false;
        }

        var params = {fieldcode:$scope.selSkillIdVal, fieldname:$scope.selSkillNameVal, description:$scope.description };
        settingService.setUserSkilled(params).then( function (response) {
            if (response.data.code == 1) {
                $scope.addSkill = false;
                response.data.data.subDesc = $scope.description;
                $scope.userSkilledList.push(response.data.data);
                //清空添加框数据
                $scope.selSkillIdVal = '';
                $scope.selSkillNameVal = '';
                $scope.description = '';
                //清空添加框数据

                return ;
            }
        });

        return false;
    }


    //编辑用户基本信息
    $scope.bsinfobjFun = function () {

        //控制部分可以编辑
        if($scope.authState == 1 || $scope.authState == 2) {
            $scope.staticState = true;
            $scope.bsinfobj = false;

        }else {
            $scope.staticState = false;
            $scope.bsinfobj = true;
        }

        $scope.allSpanState = false;
        $scope.allInputState = true;

        $scope.editBaseButtonState = false;
    }

    //取消基本信息编辑操作
    $scope.cancelBsinfobjFun = function (type) {
        //控制部分可以编辑
        if($scope.authState == 1 || $scope.authState == 2) {
            $scope.staticState = true;
            $scope.bsinfobj = false;

        } else {
            $scope.staticState = true;
            $scope.bsinfobj = false;
        }

        $scope.allSpanState = true;
        $scope.allInputState = false;

        $scope.editBaseButtonState = true;

        if(type != 1) {
          $scope.userBaseInfo = angular.copy($scope.userBaseInfo_back); //备份原始数据
        }
    }

    //保存基本信息
    $scope.saveBsinfoFun = function () {
        var params = $scope.userBaseInfo;
        //params.degreeCode = $scope.userBaseInfo.degreeCodexx.code;


        settingService.updateUserInfo( params ).then(function (response) {
            if (response.data.code == 1) {

                //设学位份名字
                for (var i=0; i<$scope.degreeList.length; i++)
                {
                    if($scope.degreeList[i].code == params.degreeCode) {
                        $scope.userBaseInfo.degreeName = $scope.degreeList[i].name;
                    }
                }
                //设学位份名字
                angular.element('.new_username').text(params.username)  //如果可以操作父级元素、可以改用操作父级元素的方式
                $scope.cancelBsinfobjFun(1);
                return ;
            }
        });
        return false;
    }

    //编辑执业信息
    $scope.workinfobjFun = function () {

        //控制部分可以编辑
        if($scope.authState == 1 || $scope.authState == 2) {
            $scope.workStaticState = true;
            $scope.workinfobj = false;

        } else {
            $scope.workStaticState = false;
            $scope.workinfobj = true;
        }

        $scope.workAllSpanState = false;
        $scope.workAllInputState = true;

        $scope.editSkillButtonState = false;
    }

    //取消执业信息编辑操作
    $scope.cancelWorkinfobjFun = function (type) {
        //控制部分可以编辑
        if($scope.authState == 1 || $scope.authState == 2) {
            $scope.workStaticState = true;
            $scope.workinfobj = false;

        } else {
            $scope.workStaticState = true;
            $scope.workinfobj = false;
        }

        $scope.workAllSpanState = true;
        $scope.workAllInputState = false;

        $scope.editSkillButtonState = true;

        if(type != 1) {
          $scope.userBaseInfo = angular.copy($scope.userBaseInfo_back);
        }
    }

    //保存执业信息
    $scope.saveWorkinfoFun = function () {

        var params = $scope.userBaseInfo;
        //params.workArea = $scope.userBaseInfo.provinceList.areaCode;
        //params. = lawfirInfo;
        if(typeof($scope.userBaseInfo.lawfirmname) == "object") {
            params.lawfirmid = $scope.userBaseInfo.lawfirmname.id;
        } else {
          $("#zylawfirmname").addClass("error");
          return false;
        }
        settingService.updateProfessionInfoNew( params ).then(function (response) {
            if (response.data.code == 1) {
                $scope.userBaseInfo.viewlawfirmname = $scope.userBaseInfo.lawfirmname.name;

                //设置省份名字
                for (var i=0; i<$scope.provinceList.length; i++)
                {
                    if($scope.provinceList[i].areaCode == params.workArea) {
                        $scope.userBaseInfo.workAreaName = $scope.provinceList[i].name;
                    }
                }
                //设置省份名字

                $scope.cancelWorkinfobjFun(1);
                return ;
            }
        });
        return false;
    }

    //获取学位信息
    function getLawfirmList () {

        if($scope.degreeList.length <= 0) {
            settingService.findDegreeList().then(function (response) {
                if (response.data.code == 1) {
                    $scope.degreeList = response.data.data;

                }
            })
        }
    }

    //获取省份
    function findProvinceList () {

        if($scope.provinceList.length <= 0) {
            settingService.findProvinceList().then(function (response) {
                if (response.data.code == 1) {
                    $scope.provinceList = response.data.data;
                }
            })
        }
    }


    //头像上传处理
    $scope.onChange=function($dataURI) {    //可选项，检测到图片修改后执行的表达式
        //console.log($dataURI);
        //$scope.file = $scope.getBlobBydataURL($dataURI,"image/png");

        /*settingService.uploadPhoto(data).then(function (response) {
            if (response.code == 1) {
                console.log("suc");
            }
        }, function (response) {
            console.log('error');
        });*/
    };

    $scope.onLoadBegin=function() { //可选项，图片开始加载执行的表达式

    };
    $scope.onLoadDone=function() {  //可选项，图片加载完成执行的表达式
        $scope.isSelectHeadPhone = true;

    };
    $scope.onLoadError=function() { //可选项，图片加载失败执行的表达式

    };

    var handleFileSelect=function(evt) {
        var file=evt.currentTarget.files[0];
        var reader = new FileReader();
        reader.onload = function (evt) {
            $scope.$apply(function($scope){
                $scope.myImage=evt.target.result;
            });
        };
        reader.readAsDataURL(file);
    };
    angular.element(document.querySelector('#fileInput')).on('change',handleFileSelect);

    //格式化图片
    $scope.getBlobBydataURL = function(dataURI,type){
        var binary = atob(dataURI.split(',')[1]);
        var array = [];
        for(var i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        return new Blob([new Uint8Array(array)], {type:type });
    }

    //执行修改头像
    $scope.uploadHeadPhone = function () {

        // console.log($scope.myCroppedImage);
        // console.log($scope.file);
        if($scope.isSelectHeadPhone === false) {

            return false;
        }

        $scope.file = $scope.getBlobBydataURL($scope.myCroppedImage,"image/png");
        var data = new FormData();
        data.append("file", $scope.file);
        data.append('fileType', "image");//文件类型
        settingService.uploadPhoto(data).then(function (response) {

            if (response.code == 1) {
                //console.log("suc");
                window.location.reload();
            }
        }, function (response) {

            console.log('error');

        })
    }
    //头像上传处理



};
